<template>
  <!-- 设备变量管理 virtualDevice -->
  <div class="mybuildingArea">
    <div class="con">
      <div class="con-left">
        <div class="top-tree top-div">
          <div class="Files-top">
            <div class="ic-left">
              <span>通讯设备列表</span>
            </div>
            <div class="btns">
            </div>
          </div>
          <div class="mytree">
            <el-scrollbar style="height:calc(100% - 10px);width: 100%;">
              <el-tree :data="channelAndDeviceTree" :default-expanded-keys="[2]" default-expand-all
                :expand-on-click-node="true" :props="defaultProps" :highlight-current='true' show-checkbox ref="tree"
                @node-click="checkItem" @check="currentChecked">
                <template  #default="{ node }">
                    <div class="custom-tree-node">
                      <img src="../../../public/static/image/elTree/2.1.png" v-if="node.data.entityName=='Device'" />
                      <img src="../../../public/static/image/elTree/2.0.png" v-else />
                      <span style="padding:0px  5px;">{{node.label }}</span>
                    </div>
                  </template>
              </el-tree>
            </el-scrollbar>
          </div>
        </div>
        <div class="mytable xia-div">
          <el-table ref="multipleTable" :data="nowDeviceVariableList" stripe max-height="100%" height="100%" border tooltip-effect="dark"
            style="width: 100%" @selection-change="lefthandleSelectionChange">
            <el-table-column type="selection" width="44" align="center" fixed></el-table-column>
            <el-table-column prop="name" label="变量名称" width="350"></el-table-column>
            <el-table-column prop="channelNo" label="通道号" width="120"></el-table-column>
            <el-table-column prop="deviceNo" label="通讯设备号" show-overflow-tooltip></el-table-column>
          </el-table>
        </div>
      </div>
      <div class="con-middle">
        <div class="top-btn top-div">
          <div class="btns">
            <!-- <div class="left-add" style=" margin-bottom: 15px; " @click="addDeviceToRight2">导入虚设备(测试)<img
                src="../../assets/right.png"></div> -->
            <div class="left-add" @click="addDeviceToRight">导入虚设备<img src="../../assets/unifyImg/right.png"></div>
            <div class="del" @click="piliangshanchu">删除虚设备<img src="../../assets/unifyImg/left.png"></div>
          </div>
        </div>
        <div class="xia-btn xia-div">
          <div class="btns">
            <div class="left-add" @click="addVariablefn">导入变量<img src="../../assets/unifyImg/right.png"></div>
            <div class="del" @click="delVariablefn">移除点表<img src="../../assets/unifyImg/left.png"></div>
          </div>
        </div>
      </div>
      <div class="con-right">
        <div class="top-div top-tree">
          <div class="Files-top">
            <div class="ic-left">
              <span>虚拟设备列表</span>
            </div>
            <div class="btns">
              <el-button type="primary" style="position: relative;" v-show="isArea"><input
                  class="inp" ref="inp" type="file" @change="uploadExcel" />导入</el-button>
              <el-button type="primary" v-show="isArea" @click='addDevice'>添加设备</el-button>
              <el-button type="primary" v-show="isArea" @click="addGroup">添加组</el-button>
              <el-button type="primary" @click="editGroup" 
              v-show="isArea && nowCheckedItem != undefined && nowCheckedItem.entityName == 'AppClassType'">修改组</el-button>
              <el-button type="primary" @click="editdecicenamefn" 
              class="last-el-button" v-if="!isArea && nowCheckedItem != undefined && nowCheckedItem.entityName != 'AppClassType'">修改设备</el-button>
              <el-button type="primary" class="last-el-button del-btn-transfer" @click="deleteOperate" 
              v-show="isArea &&  nowCheckedItem != undefined">删除</el-button>
               <el-button type="primary" class="last-el-button del-btn-transfer" style="margin-left:12px !important;" @click="deleteshebei" 
              v-show="!isArea && shanchudevice">删除设备</el-button>
              
            </div>
          </div>
          <div class="mytree">
            <el-scrollbar style="height:calc(100% - 10px);width: 100%;">
              <el-tree :data="channelAndVirtualDeviceTree" :default-expanded-keys="[2]" default-expand-all
                :expand-on-click-node="false" :props="defaultProps" :highlight-current='true' show-checkbox ref="tree"
                @node-click="checkItemTwo" @check="currentCheckeddel">
                <template  #default="{ node }">
                  <div class="custom-tree-node">
                    <img src="../../../public/static/image/elTree/1.9.png"
                      v-show="node.data.entityName=='AppClassType'&&node.data.unitid!=''&&node.data.unitid != null" />
                    <img src="../../../public/static/image/elTree/2.0.png"
                      v-show="node.data.entityName=='AppClassType'&&(node.data.unitid=='' || node.data.unitid == null)" />
                    <img src="../../../public/static/image/elTree/2.0.png" v-show="!node.data.entityName" />
                    <img src="../../../public/static/image/elTree/2.1.png" v-show="node.data.type=='virtualDevice'" />
                    <span style="padding:0px  5px;">{{node.label }}</span>
                  </div>
                </template>
              </el-tree>
            </el-scrollbar>
          </div>
        </div>
        <div class="xia-div mytable">
          <el-table ref="multipleTable" :data="nowDeviceVariableListTwo" stripe max-height="100%" height="100%" border
            tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="44" align="center" fixed></el-table-column>
            <el-table-column prop="name" label="变量名称" width="350"></el-table-column>
            <el-table-column prop="fromConnect" label="通道号" width="120"></el-table-column>
            <el-table-column prop="fromObject" label="虚拟设备号" show-overflow-tooltip></el-table-column>
          </el-table>
        </div>
      </div>
    </div>
      <div class="el-loading-mask" v-show="logingflag">
                                    <div class="el-loading-spinner">
                                      <svg viewBox="25 25 50 50" class="circular">
                                          <circle cx="50" cy="50" r="20" fill="none" class="path"></circle>
                                      </svg>
                                      
                                   </div>
                                   
         </div>
     <div class="el-loading-mask" v-show="logingindex">
                                    <div class="el-loading-spinner">
                                      <svg viewBox="25 25 50 50" class="circular">
                                          <circle cx="50" cy="50" r="20" fill="none" class="path"></circle>
                                      </svg>
                                      <div>{{myindex}} / {{checkedNodes.length}}</div>
                                   </div>
                                   
         </div>
           <div class="el-loading-mask" v-show="logingindex2">
                                    <div class="el-loading-spinner">
                                      <svg viewBox="25 25 50 50" class="circular">
                                          <circle cx="50" cy="50" r="20" fill="none" class="path"></circle>
                                      </svg>
                                      <div>{{myindexdel}} / {{checkedNodesdel.length}}</div>
                                   </div>
                                   
         </div>
          <!-- 修改设备名称 -->
        <el-dialog draggable title="修改设备名称" :close-on-click-modal='false' v-model="dialogVisibledev"
                width="400px" >
                 <div class="dialogcon">
                        <div class="operateitem" style="display:flex;align-items: center;">
                            <span style="white-space: nowrap;">设备名称：</span>
                            <el-input v-model="inputname"></el-input>
                        </div>
                    </div>
                <template #footer>
                    <span class="dialog-footer">
                    <el-button @click="dialogVisibledev = false">取 消</el-button>
                    <el-button type="primary" class="last-el-button" @click="quedingEdit">确 定
                    </el-button>
                    </span>
                </template>
          </el-dialog>
    <!-- 新增修改 -->
    <el-dialog draggable :title="textMap[dialogStatus]" :close-on-click-modal='false' v-model="dialogVisible"
      width="400px" center>
      <div style="display: flex;">
        <el-form :model="temp" ref="temp" :rules="rules" style="width: 100%;height: 60px;padding-top: 10px;">
          <el-form-item label="名称:" prop="name">
            <el-input v-model="temp.name" style=""></el-input>
          </el-form-item>
        </el-form>

      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogStatus==='edit'?edit_fn('temp'):add_fn('temp')">确 定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import {saveVariable,deleteVariable,getChannelAndDeviceTreeapi,getChannelAndVirtualDeviceTreeapi} from "../../api/energySubType";
  import {getGenerallyVariableByDeviceNoLimitfn,getVariableListfn,saveAppClassType,deleteAppClassType,updateVirtualDeviceName,deleteshebei} from "../../api/abbNewApi";
  import request from "../../api/htttp2.js";

  export default {
    components: {
    },
    props: {},
    data () {
      return {
        inputname:"",
        dialogVisibledev:false,
        logingflag:false,
        nowCheckedVariable:{},
        checkedNodes:[],
        channelAndDeviceTree: [],
        channelAndVirtualDeviceTree: [],
        nowDeviceVariableList: [],
        nowDeviceVariableListTwo: [],
        isContainer: false,
        isArea: false,
        nowCheckedItem: undefined,
        newSort: 0,
        defaultProps: {
          children: 'next',
          label: 'name'
        },
        multipleSelection: [],
        rules: {
          name: [
            {required: true,message: '请输入名称',trigger: 'blur'}
          ],
        },
        dialogVisible: false,
        dialogStatus: '',
        temp: {},
        textMap: {
          addGroup: "添加组",
          addDevice: "添加设备",
          edit: "修改名称",
        },
        lableMap: {
          addGroup: "组名称：",
          addDevice: "设备名称：",
          edit: "新名称：",
        },
        newName: "",
        myindex:0,
        logingindex:false,
        checkedNodesdel:[],
        myindexdel:0,
        logingindex2:false,
        leftTableVar:[],
        rightTableVar:[],
        shanchudevice:false,
      }
    },
    created () {},
    mounted () {
      this.getChannelAndDeviceTree()
      this.getChannelAndVirtualDeviceTree()
    },
    destroyed () {},
    computed: {
      
    },

    methods: {
      
      //导入
      uploadExcel (evt) {
        const files=evt.target.files;
        if(files==null||files.length==0) {
          alert("没有文件等待导入");
          return;
        }

        let name=files[0].name;

        let suffixArr=name.split("."),suffix=suffixArr[suffixArr.length-1];
        if(suffix!="xlsx") {
          this.$message({showClose: true,message: `当前仅支持导入xlsx文件`,type: 'warning'});
          return;
        }

        var params={
          parentarea: this.nowCheckedVariable.parentarea,
          groupNo: this.nowCheckedItem.no,
          generallyNo: this.nowCheckedVariable.no,
          deviceNo: this.nowCheckedVariable.no,
          file: files[0],
        }
        var data=new FormData();
        for(const key in params) {
          data.append(key,params[key]);
        }
        request({url: "/virtualDevice/importVirtualDevice",method: "post",data}).then(res => {
          this.$refs.inp.value=''
          if(res.success) {
            this.$message({showClose: true,type: 'success',message: '添加成功！'});
            this.getChannelAndVirtualDeviceTree()
          } else {
            this.$message({showClose: true,type: 'info',message: res.message,duration: 5000});
          }
        })

      },
      lefthandleSelectionChange(val){
      //  console.log("通讯设备",val);
       this.leftTableVar = val;
      },
      handleSelectionChange (val) {
        // console.log("虚拟设备",val);
        this.rightTableVar = val;
      },
      //导入变量
      addVariablefn(){
          if(this.leftTableVar.length == 0){
             return
          }
          if(this.nowCheckedItem.entityName != 'VirtualDevicePojo'){
               this.$message({showClose: true,type: 'warning',message: '请选择虚拟设备'});
               return
          }
          if(this.nowCheckedItem == undefined){
               this.$message({showClose: true,type: 'warning',message: '请选择虚拟设备'});
               return
          }
          var dd = []
          this.leftTableVar.forEach(item => {
              dd.push({
                "fromName": item.name,
                "fromconnect": item.channelNo,
                "parentArea": 0,
                "virtualName": this.nowCheckedItem.name,
                "virtualNo": this.nowCheckedItem.no
              })
          })
          this.logingflag = true
          saveVariable(dd).then(res => {
            this.logingflag = false
               if(res.code == 200){ 
                   this.$message({showClose: true,type: 'warning',message: '操作成功'});
                   this.getGenerallyVariableByDeviceNoLimit(this.nowCheckedVariable)
               }else {
                   this.$message({showClose: true,type: 'error',message: '操作失败'});
               }
          })
      },
      //删除变量
      delVariablefn(){
         if(this.rightTableVar.length == 0){
             return
          }
         this.$confirm(`确定要删除选中的变量吗?`,'提示',{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.logingflag = true
          var idArr = []
          this.rightTableVar.forEach(item => {
              idArr.push(item.id)
          })

          deleteVariable({'pkids':idArr.join()}).then(res => {
            this.logingflag = false
             if(res.code == 200){ 
                   this.$message({showClose: true,type: 'warning',message: '操作成功'});
                   this.getVariableList(this.nowCheckedItem)
               }else {
                   this.$message({showClose: true,type: 'error',message: '操作失败'});
               }
          })
        }).catch(() => {
          this.$message({
            showClose: true,
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      //删除点表
      //添加组弹窗
      addGroup () {
        this.dialogStatus='addGroup';
        this.dialogVisible=true;
        this.$nextTick(() => {
          this.$refs["temp"].clearValidate();
        });
        this.temp={};
      },
      // 添加设备弹窗
      addDevice () {
        this.dialogStatus='addDevice';
        this.dialogVisible=true;
        this.$nextTick(() => {
          this.$refs["temp"].clearValidate();
        });
        this.temp={};
      },
      // 确认添加
      add_fn (formName) {
        // console.log(this.dialogStatus,'dialogStatus');
        this.$refs[formName].validate(valid => {
          if(valid) {
            if(this.dialogStatus=='addGroup') {//添加组
              var data = {
                 no:undefined, 
                 name:this.temp.name, 
                 fatherno:this.nowCheckedItem.no, 
                 unitId:undefined, 
                 sort:this.newSort, 
                 devicetype:0
              }
              saveAppClassType(data).then(res => {
                  if(res.success){
                    this.$message({showClose: true,showClose: true,message: '添加组：'+res.data.name+' 成功！',type: 'success'});
                    this.getChannelAndVirtualDeviceTree()
                    this.dialogVisible=false
                  }else {
                     this.$message({showClose: true,showClose: true,message: '添加失败',type: 'error'});
                  }
              })
            } else {//addDevice 添加设备
               var params={
                  name: this.temp.name,
                  groupNo: this.nowCheckedItem.no,
                  parentarea: 0,
                }
                var data=new FormData();
                for(const key in params) {
                  data.append(key,params[key]);
                }
                request({url: "/virtualDevice/saveVirtualDevice.do",method: "post",data}).then(res => {
                  if(res.success){
                    this.$message({showClose: true,type: 'success',message: '添加成功！'});
                     this.dialogVisible=false
                    this.getChannelAndVirtualDeviceTree()
                  }else {
                     this.$message({showClose: true,showClose: true,message: err,type: 'error'});
                  }
                 
                })
            }

          } else {
            return false;
          }
        });
      },
      editdecicenamefn(){
        this.inputname = JSON.parse(JSON.stringify(this.nowCheckedItem.name))
        this.dialogVisibledev = true
      },
      //修改弹窗
      editGroup () {
        this.dialogStatus="edit";
        this.temp=Object.assign({},this.nowCheckedItem);
        this.dialogVisible=true;
        this.$nextTick(() => {
          this.$refs["temp"].clearValidate();
        });
      },
      // 确认编辑
      edit_fn () {
        this.$refs['temp'].validate(valid => {
          if(valid) {
              var data = {
                 no:this.nowCheckedItem.no, 
                 name:this.temp.name, 
                 fatherno:this.nowCheckedItem.fatherno, 
                 unitId:this.nowCheckedItem.unitid, 
                 sort:this.nowCheckedItem.sort, 
                 devicetype:this.nowCheckedItem.devicetype
              }
              saveAppClassType(data).then(res => {
                this.dialogVisible=false
                  if(res.success){
                    this.$message({showClose: true,type: 'success',message: '修改成功！'});
                    this.getChannelAndVirtualDeviceTree()
                  }else {
                     this.$message({showClose: true,type: 'error',message: '修改失败'});
                  }
              })
          } else {
            return false;
          }
        });
      },
       //确定修改虚拟设备名称
      quedingEdit(){
        var params = {
          no:this.nowCheckedItem.no,
          name:this.inputname,
        }
        updateVirtualDeviceName(params).then(res => {
            // console.log("修改",res);
            if(res.code == 200){
              this.dialogVisibledev = false
              this.getChannelAndVirtualDeviceTree()
              this.$message({type: 'success',message: '修改成功'})
            }else {
              this.$message({type: 'error',message: `修改失败,${res.message}`});
            }
        })
      },



      // 删除组
      deleteOperate () {
        if(this.nowCheckedItem.entityName == 'VirtualDevicePojo'){
           this.$message({showClose: true,type: 'warning',message: '请选择需要删除的设备组'});
           return
        }
        if(!isempty(this.nowCheckedItem.unitid)&&this.nowCheckedItem.unitid!=undefined) {
          this.$message({showClose: true,type: 'error',message: '当前组不可删除'});
          return
        }
        this.$confirm(`确定要删除 ${this.nowCheckedItem.name}吗?`,'提示',{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if(this.nowCheckedItem.entityName!='VirtualDevicePojo') {
            this.logingflag = true
            deleteAppClassType({no:this.nowCheckedItem.no}).then(res => {
               this.dialogVisible=false;
               this.logingflag = false
               if(res.success){
                 this.$message({showClose: true,type: 'success',message: '删除组：'+this.nowCheckedItem.name+' 成功！'});
                 this.getChannelAndVirtualDeviceTree()
               }else {
                  this.$message({showClose: true,type: 'error',message: '删除组失败！'});
               }
            })
          }
        }).catch(() => {
          this.$message({
            showClose: true,
            type: 'info',
            message: '已取消删除'
          });
        });


      },
      //删除设备
      deleteshebei(){
         this.$confirm(`确定要删除 ${this.nowCheckedItem.name}吗?`,'提示',{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            this.logingflag = true
            deleteshebei({no:this.nowCheckedItem.no}).then(res => {
               this.dialogVisible=false;
               this.logingflag = false
               if(res.success){
                 this.$message({showClose: true,type: 'success',message: '删除设备：'+this.nowCheckedItem.name+' 成功！'});
                 this.getChannelAndVirtualDeviceTree()
               }else {
                  this.$message({showClose: true,type: 'error',message: '删除设备失败！'});
               }
            })
          
        }).catch(() => {
         
        });
          
      },
      //批量删除
      delexecuteApi(index) {
      // this.myindex = index
      this.myindexdel = index
      // 检查是否到达数组末尾
      if (index >= this.checkedNodesdel.length) {
        this.logingindex2 = false
        this.$message({showClose: true,type: 'success',message: '删除成功！'});
        this.getChannelAndVirtualDeviceTree()
        return; // 结束链式调用
      }
     
      // 假设这个URL是你要调用的API的URL，并且item是你需要传递给API的数据
      const url = `${localStorage.getItem("baseURL2")}/virtualDevice/deleteVirtualDevice.do`;
       var ddd= new FormData()
      // ddd.append('no',undefined)
      ddd.append('no',this.checkedNodesdel[index].no)
      // 发送请求
      fetch(url, {
        method: 'post', // 或者 'POST'
        headers: {
          'token': localStorage.getItem("token"), // 根据API的要求调整
          // 'Content-Type': 'application/x-www-form-urlencoded', // 根据API的要求调整
          // 如果需要的话，可以添加其他头部信息
        },
        body: ddd // 将JavaScript对象转换为JSON字符串
      })
      .then(response => {
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          // 解析JSON格式的响应数据
          return response.json();
        })
      .then(data => {
        // this.leftDeviceArr = this.leftDeviceArr.concat(data.data)
        this.delexecuteApi(index + 1); // 请求下一个元素
      })
      .catch(error => {
        console.error(`Error executing API for item ${this.checkedNodes[index]}:`, error);
        // 处理错误，例如中断链式调用
      });
     },
     //批量删除虚设备
     piliangshanchu(){
       
       if(this.checkedNodesdel.length != 0){
         this.$confirm(`确定要删除选中的设备吗?`,'提示',{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.logingindex2 = true
           this.delexecuteApi(0);
        }).catch(() => {
          this.$message({
            showClose: true,
            type: 'info',
            message: '已取消删除'
          });
        });
         
          // return
       }else {
          this.$message({showClose: true,type: 'warning',message: '请选择需要删除的设备'});
       }
     },

      // 刷新
      refresh () {
        this.getChannelAndDeviceTree()
        this.getChannelAndVirtualDeviceTree()
      },
      autoSelectMethod (item,index) {
        return item.entityName=='Device'
      },
      isGroup (item) {
        return item.hasOwnProperty('next')
      },
     //树形结构选中节点
		currentChecked (nodeObj, SelectedObj) {
              this.checkedNodes = SelectedObj.checkedNodes.filter(item => item.entityName == 'Device')
            },
      //左边树形结构点击
      checkItem (item) {
        // console.log("点击",item);
        if(item.entityName=='Device') {
          this.nowCheckedVariable = item
          this.nowDeviceVariableList=[]
          this.checkedNodes = [item]
          this.getGenerallyVariableByDeviceNoLimit(item)
        }

      },
      //右边树形结构点击
      checkItemTwo (item) {
        // console.log("右边点击",item);
        this.nowDeviceVariableListTwo=[]
        this.nowCheckedItem=item
        this.isContainer=item.no==0? true:false
        if(isempty(item.next)||item.next==undefined) {
          this.newSort=1
        } else {
          var sort=0
          for(let i=0;i<item.next.length;i++) {
            if(item.next[i].sort>sort) {
              sort=item.next[i].sort
            }
          }
          this.newSort=sort+1
        }
        // console.log("item",item);
        if(item.entityName=='VirtualDevicePojo') {
          this.isArea=false
          this.getVariableList(item)
          if(item.type == 'virtualDevice'){
             this.shanchudevice = true
          }else {
             this.shanchudevice = false
          }
        } else {
          this.isArea=true
           this.shanchudevice = false
        }
      },
      //虚拟设备树形勾选
      currentCheckeddel(value,SelectedObj){
        var checkedNodes = SelectedObj.checkedNodes;
        this.checkedNodesdel = checkedNodes.filter(
          (item) => item.entityName == "VirtualDevicePojo"
        );
      },
      //导入虚设备
      addDeviceToRight2 () {
        var params={
          name: this.nowCheckedVariable.name,
          groupNo: this.nowCheckedItem.no,
          generallyNo: this.nowCheckedVariable.no,
          parentarea: this.nowCheckedVariable.parentarea,
        }
        var data=new FormData();
        for(const key in params) {
          data.append(key,params[key]);
        }
        request({url: "/virtualDevice/saveIrregularVirtualDevice",method: "post",data}).then(res => {
          this.$message({showClose: true,type: 'success',message: '添加成功！'});
          this.getChannelAndVirtualDeviceTree()
        })
      },
      //虚拟设备列表
      executeApi(index) {
        this.myindex = index
      // 检查是否到达数组末尾
      if (index >= this.checkedNodes.length) {
        this.logingindex = false
         this.getChannelAndVirtualDeviceTree()
        this.$message({showClose: true,type: 'success',message: '添加成功！'});
        return; // 结束链式调用
      }
     
      // 假设这个URL是你要调用的API的URL，并且item是你需要传递给API的数据
      const url = `${localStorage.getItem("baseURL2")}/virtualDevice/saveVirtualDevice.do`;

      // 创建一个FormData对象或者直接使用对象作为数据
      const data = {
        no:undefined,
        name: this.checkedNodes[index].name,
        groupNo: this.nowCheckedItem.no,
        generallyNo: this.checkedNodes[index].no,
        parentarea: this.checkedNodes[index].parentarea,
        // ...其他POST请求所需的数据
      };
      var ddd= new FormData()
      // ddd.append('no',undefined)
      ddd.append('name',this.checkedNodes[index].name)
      ddd.append('groupNo',this.nowCheckedItem.no)
      ddd.append('generallyNo',this.checkedNodes[index].no)
      ddd.append('parentarea',this.checkedNodes[index].parentarea)


      // 发送POST请求
      fetch(url, {
        method: 'POST', // 或者 'POST'
        headers: {
          'token': localStorage.getItem("token"), // 根据API的要求调整
          // 'Content-Type': 'application/x-www-form-urlencoded', // 根据API的要求调整
          // 如果需要的话，可以添加其他头部信息
        },
        body: ddd // 将JavaScript对象转换为JSON字符串
      })
      .then(data => {
        // console.log(`API executed for item ${this.checkedNodes[index]}:`,new Date().getTime());
        this.executeApi(index + 1); // 请求下一个元素
      })
      .catch(error => {
        console.error(`Error executing API for item ${this.checkedNodes[index]}:`, error);
        // 处理错误，例如中断链式调用
      });
    },
      // this.processArray(); // 组件挂载后开始处理数组
      //导入虚设备
      addDeviceToRight () {
         if(this.nowCheckedItem == undefined || this.nowCheckedItem.entityName == 'VirtualDevicePojo'){
           this.$message({showClose: true,type: 'warning',message: '请选择虚拟设备组'});
           return
        }
        if(this.checkedNodes.length != 0){
             this.logingindex = true
             this.executeApi(0);
        }else {
           this.$message({showClose: true,type: 'warning',message: '请选择设备'});
        }
        
      },
      
      getChannelAndDeviceTree () {
        this.logingflag = true
        getChannelAndDeviceTreeapi().then(res => {
          this.logingflag = false
           if(res.success){
             this.channelAndDeviceTree=[res.data]
           }
        })
        
      },
      getChannelAndVirtualDeviceTree () {
         this.logingflag = true
         getChannelAndVirtualDeviceTreeapi().then(res => {
            this.logingflag = false
            if(res.success){
             this.channelAndVirtualDeviceTree=[res.data]
            //  console.log("数据",this.channelAndVirtualDeviceTree);
              // this.$store.deviceStore.commit("getReadDeviceTree")
           }
         })
       
      },
      getGenerallyVariableByDeviceNoLimit (item) {
        var data = {
           'deviceNo':item.id,
           'pageIndex':1,
           'pageSize':10000,
        }
        getGenerallyVariableByDeviceNoLimitfn(data).then(res => {
          this.nowDeviceVariableList=res.data.data
        })
        
      },
      getVariableList (item) {
        var data = {
           deviceNo:item.no
        }
        getVariableListfn(data).then(res => {
            this.nowDeviceVariableListTwo=res.data
        })
      },
      getAddedDeviceNos (list,arr) {
        for(let i=0;i<list.length;i++) {
          if(list[i].entityName!=undefined&&list[i].entityName=='VirtualDevicePojo') {
            arr.push(list[i].no)
          } else if(!isempty(list[i].next)) {
            this.getAddedDeviceNos(list[i].next,arr)
          }
        }
      }
    }
  }
</script>
<style>
  .el-message__closeBtn {
    top: 18px !important;
  }
</style>
<style scoped lang="scss">
.mybuildingArea {
   position: relative;
}
:deep(.el-scrollbar__view) {
   width: 99%;
}
  .inp {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    opacity: 0;
  }

  .con {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    display: flex;

    .top-div {
      width: 100%;
      height: 477px;
      margin-bottom: 4px;
      background-color: #fff;
    }

    .xia-div {
      width: 100%;
      height: calc(100% - 481px);
      background-color: #fff;

    }

    .mytree {
      width: 100%;
      height: calc(100% - 35px);
    }

    .con-left {
      width: calc(50% - 75px);
      height: 100%;

      .top-tree {
        padding: 12px;
        box-sizing: border-box;
      }

      .mytable {
        padding: 12px;
        box-sizing: border-box;

      }
    }

    .con-middle {
      width: 140px;
      height: 100%;
      margin: 0px 4px;
      min-width: 140px;

      .top-btn,
      .xia-btn {
        display: flex;
        align-items: center;
        justify-content: center;

        img {
          margin-left: 10px;
        }

        .left-add,
        .del {
          width: 116px;
          height: 32px;
          background-color: #368ED9;
          color: #fff;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 2px;
        }

        .del {
          background-color: #ED6547;
          margin-top: 20px;
        }
      }

      .xia-btn {}
    }

    .con-right {
      width: calc(50% - 75px);
      height: 100%;

      .Files-top {
        padding-bottom: 6px !important;
      }

      .top-tree {
        padding: 12px;
        box-sizing: border-box;
      }

      .mytable {
        padding: 12px;
        box-sizing: border-box;

      }
    }
  }

  :deep(.el-dialog__header) {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #E6E6E6;

    span {
      color: #67A3ED;
      font-size: 14px;
      font-weight: bold;
    }

    .el-icon-close {
      font-size: 20px !important;
    }

  }

  :deep(.el-dialog__footer) {
    margin-top: 20px;
    text-align: right !important;
    border-top: 1px solid #E6E6E6;

    button {
      padding: 8px 17px;
    }
  }

  .demo-temp {
    display: flex;
    flex-wrap: wrap;
  }

  :deep(.el-form-item) {
    display: flex;
    margin-left: 20px;
  }

  :deep(.el-form-item__label) {
    white-space: nowrap;
    width: 86px;
  }

  :deep(.el-dialog__body) {
    padding: 20px 20px 0px 20px !important;
  }
</style>